package com.example.studentportrait.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.studentportrait.constants.SystemConstants;
import com.example.studentportrait.domain.ResponseResult;
import com.example.studentportrait.domain.entity.AssessmentQuestion;
import com.example.studentportrait.domain.entity.Employer;
import com.example.studentportrait.domain.entity.School;
import com.example.studentportrait.domain.vo.PageVo;
import com.example.studentportrait.enums.AppHttpCodeEnum;
import com.example.studentportrait.mapper.EmployerMapper;
import com.example.studentportrait.mapper.SchoolMapper;
import com.example.studentportrait.service.EmployerService;
import com.example.studentportrait.service.SchoolService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import static com.example.studentportrait.enums.AppHttpCodeEnum.SYSTEM_ERROR;

/**
 * 雇佣方表(Role)表服务实现类
 *
 * @author makejava
 * @since 2023-10-17 21:18:32
 */
@Service("schoolService")
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {

    //新增学校
    @Override
    public ResponseResult addSchool(School school) {
        save(school);
        return ResponseResult.okResult();
    }

    //编辑学校
    @Override
    public ResponseResult updateSchool(School school) {
        UpdateWrapper<School> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",school.getId())
                .eq("is_delete", SystemConstants.NOT_DELETE)
                .set(StringUtils.hasText(school.getSchoolName()),"school_name",school.getSchoolName())
                .set(StringUtils.hasText(school.getSchoolLevel()),"school_level",school.getSchoolLevel())
                .set(StringUtils.hasText(school.getSchoolAcronym()),"school_acronym",school.getSchoolAcronym());

                boolean updateState=update(updateWrapper);
        if(!updateState){
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR,"学校编辑失败或不存在");
        }
        return ResponseResult.okResult("学校编辑成功");
    }

    //删除学校
    @Override
    public ResponseResult deleteSchool(Long id) {
        UpdateWrapper<School> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",id)
                .eq("is_delete",SystemConstants.NOT_DELETE)
                .set("is_delete",SystemConstants.DELETE);

        boolean deleteState=update(updateWrapper);
        if(!deleteState){
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_ERROR,"学校删除失败或不存在");
        }
        return ResponseResult.okResult("学校删除成功");
    }

    //查询学校
    @Override
    public ResponseResult schoolList(Integer pageNum, Integer pageSize, School school) {
        LambdaQueryWrapper<School> lqw=new LambdaQueryWrapper<>();
        lqw.eq(School::getIsDelete,SystemConstants.NOT_DELETE);
        lqw.eq(StringUtils.hasText(school.getSchoolCode()),School::getSchoolCode,school.getSchoolCode());
        lqw.like(StringUtils.hasText(school.getSchoolName()),School::getSchoolName,school.getSchoolName());
        lqw.eq(StringUtils.hasText(school.getSchoolLevel()),School::getSchoolLevel,school.getSchoolLevel());

        Page<School> page=new Page<>(pageNum,pageSize);
        page(page,lqw);

        List<School> schoolList = page.getRecords();
        if(schoolList.isEmpty()){
            return ResponseResult.okResult(new PageVo(Collections.emptyList(),0L));
        }
        PageVo pageVo = new PageVo(schoolList, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    //批量删除学校
    @Override
    public ResponseResult deleteSchoolList(List<Long> ids) {
        // 判断 ids 是否为空
        if (ids == null || ids.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CONTENT_NOT_NULL, "没有要删除的学校ID");
        }

        // 批量更新 is_delete 字段为 1（删除状态）
        UpdateWrapper<School> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids).set("is_delete", SystemConstants.DELETE);

        // 执行更新操作
        boolean updateSuccess = update(updateWrapper);

        // 判断更新是否成功
        if (updateSuccess) {
            return ResponseResult.okResult("批量删除学校成功");
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "批量删除学校失败");
        }
    }

    //通过文件导入学校
    @Override
    public ResponseResult insertSchoolListByExcel(MultipartFile file) {
        try (InputStream excelFile = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(excelFile)) {
            List<School> schoolList = new ArrayList<>();

            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            // 跳过第一行
            if (rowIterator.hasNext()) {
                rowIterator.next();
            }

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                List<String> cellValues = new ArrayList<>();

                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    if (cell == null) {
                        cellValues.add("");
                    } else {
                        switch (cell.getCellTypeEnum()) {
                            case STRING:
                                cellValues.add(cell.getStringCellValue());
                                break;
                            case NUMERIC:
                                cellValues.add(String.valueOf(cell.getNumericCellValue()));
                                break;
                            default:
                                cellValues.add(""); // 处理其他类型或未知类型
                        }
                    }
                }
                // 检查并处理空字符串
                School school = new School();

                if (!cellValues.get(0).isEmpty()) {
                    school.setSchoolCode(String.valueOf((int) Double.parseDouble(cellValues.get(0))));
                }
                school.setSchoolName(cellValues.get(1));
                if (!cellValues.get(2).isEmpty()) {
                    try {
                        // 尝试将该字段值解析为数字，如果是数字，则转换为整数
                        String schoolLevel = cellValues.get(2);
                        if (schoolLevel.matches("^-?\\d+(\\.\\d+)?$")) { // 使用正则表达式检查是否是数字
                            school.setSchoolLevel(String.valueOf((int) Double.parseDouble(schoolLevel)));
                        } else {
                            // 如果不是数字，直接将其作为字符串处理
                            school.setSchoolLevel(schoolLevel);
                        }
                    } catch (NumberFormatException e) {
                        // 如果出现转换错误，直接按原始字符串处理
                        school.setSchoolLevel(cellValues.get(2));
                    }
                }
                school.setSchoolAcronym(cellValues.get(3));

                System.out.println("=========================================");
                System.out.println(school);
                schoolList.add(school);
            }

            for (School school : schoolList) {
                save(school);
            }

            return ResponseResult.okResult("学校添加成功！！！！");
        } catch (Exception exception) {
            log.error("Error:" + exception);
            return ResponseResult.errorResult(SYSTEM_ERROR);
        }
    }

}

